﻿using LiteDB;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestLiteDB
{
    public partial class TestLiteDB : Form
    {
        public TestLiteDB()
        {
            InitializeComponent();
            
        }

        public static LiteDatabase _db = null;
        /// <summary>
        /// add static method to append log to richtext box.
        /// </summary>
        public async void AppendTextAsync(string str)
        {

            await Task.Run(() =>
            {

                this.Invoke((Action)delegate
                {
                    this.richTextBox1.AppendText("[" + DateTime.Now.Ticks + "]  " + str + "\r\n");
                });

            });

        }
        public class Customer
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Name2 { get; set; }
            public string[] Phones { get; set; }
            public bool IsActive { get; set; }
            public bool IsActive2 { get; set; }
        }

        public string CheckLimits(string name)
        {


            return "";
        }

        public  LiteDatabase getInstance()
        {
           // if (_db != null) return _db;
            String path = "Filename=" + Application.StartupPath + "/TestDb2.db;Password=hzh1660;";
            _db = new LiteDatabase(path);
            _db.Log.Level = Logger.FULL;
            _db.Log.Logging += Log_Logging;
            return _db;
        }

        private  void Log_Logging(string obj)
        {
            AppendTextAsync(obj);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="db"></param>
        /// <returns></returns>
        public async void TestCollecgtionNames(LiteDatabase db)
        {

            await Task.Run(() =>
            {
                DateTime start = DateTime.Now;


                try
                {
                    foreach (var _name in db.GetCollectionNames())
                    {
                        if (!db.DropCollection(_name))
                        {
                            AppendTextAsync("drop " + _name + " false");
                        }
                    }
                    int _i = int.Parse(textBox1.Text);
                    for (int i = _i; i < 5000; i++)
                    {
                        var col = db.GetCollection<Customer>("" + i);

                        for (int j = 0; j < 2; j++)
                        {
                            // Create your new customer instance
                            var customer = new Customer
                            {
                                Name = "John Doe",
                                Name2 = "John Doe2",
                                Phones = new string[] { "8000-0000", "9000-0000" },
                                IsActive = true
                            };
                            // Insert new customer document (Id will be auto-incremented)
                            col.Insert(customer);
                        }


                        AppendTextAsync("" + i);
                    }


                }
                catch (Exception exp)
                {
                    AppendTextAsync(exp.Message);

                }
                DateTime end = DateTime.Now;
                AppendTextAsync(end.Subtract(start).ToString());




            });

        }

        private void button1_Click(object sender, EventArgs e)
        {

            // Open database (or create if doesn't exist)
            //  String path = Application.StartupPath + "/TestDb.db";
            var db = getInstance();


            // Get a collection (or create, if doesn't exist)
            var col = db.GetCollection<Customer>("customers");


            // Create your new customer instance
            var customer = new Customer
            {
                Name = "John Doe",
                Name2 = "John Doe2",
                Phones = new string[] { "8000-0000", "9000-0000" },
                IsActive = true,
                IsActive2 = false
            };

            // Insert new customer document (Id will be auto-incremented)
            col.Insert(customer);

            // Update a document inside a collection
            customer.Name = "Joana Doe";

            col.Update(customer);

            // Index document using document Name property
            col.EnsureIndex(x => x.Name);

            // Use LINQ to query documents
            var results = col.Find(x => x.Name.StartsWith("Jo"));
            foreach (var item in results)
            {
                AppendTextAsync("1-" + item.Name+";id="+item.Id);
                //item.Phones.
               

            }
          //  LiteFileInfo t;
            

            AppendTextAsync(db.Log.Level.ToString());

            



        }

        private void button2_Click(object sender, EventArgs e)
        {
            AppendTextAsync("1");
            // Open database (or create if doesn't exist)
            String path = "Filename=" + Application.StartupPath + "/TestDb.db;Password=hzh;Log=" + Logger.ERROR;
            using (var db = new LiteDatabase(path))
            {

                // TestCollecgtionNames(db);

            }
            AppendTextAsync("2");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            var db = getInstance();
            foreach (var _name in db.GetCollectionNames())
            {
                if (!db.DropCollection(_name))
                {
                    AppendTextAsync("drop " + _name + " false");
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Child _t = new Child();
            Child _t2 = new Child();
            _t.MdiParent = this;
            //_t2.Parent = _t;
            _t.Show();
            
        }
    }
}
